<template>
  <div class="p-3">
    <a-card class="w-full" style="height: 830px">
      <a-form layout="inline" :model="searchForm">
        <a-form-item label="操作人" name="operator">
          <a-tree-select
            v-model:value="searchForm.operator"
            tree-data-simple-mode
            allow-clear
            style="width: 260px"
            :dropdown-style="{ maxHeight: '400px', overflow: 'auto' }"
            :tree-data="selectList"
            placeholder="请选择操作人"
            :load-data="onLoadData"
          />
        </a-form-item>
        <a-form-item label="归属机构" name="comId">
          <a-tree-select
            v-model:value="searchForm.comId"
            tree-node-filter-prop="label"
            style="width: 260px"
            :dropdown-style="{ maxHeight: '400px', overflow: 'auto' }"
            :tree-data="comanyList"
            placeholder="请选择归属机构"
          />
          <!-- <a-tree-select
                v-model:value="searchForm.comId"
                style="width: 320px"
                :tree-data="comanyList"
                allow-clear
                placeholder="请选择归属机构"
                tree-node-filter-prop="label"
                :load-data="onLoadDatas"
                tree-checkable
              /> -->
        </a-form-item>
        <a-form-item label="文件名">
          <a-input :value="searchForm.fileName" placeholder="请输入" />
        </a-form-item>
        <!-- <a-form-item label="文件类型">
          <a-select
            allowClear
            :options="fileTypeOptions"
            v-model="searchForm.fileType"
            placeholder="请选择"
          />
        </a-form-item> -->
        <a-form-item label="导入结果">
          <DictSelect
            v-model="searchForm.importStatus"
            dictType="4"
            placeholder="请选择"
            :width="120"
            allowClear
          />
        </a-form-item>
        <a-form-item label="导入日期">
          <a-date-picker
            :value="searchForm.importDate"
            placeholder="请选择日期"
            style="width: 200px"
          />
        </a-form-item>
        <a-form-item>
          <a-button type="primary" @click="handleSearch"
            ><SearchOutlined />查询</a-button
          >
        </a-form-item>
        <a-form-item>
          <a-button @click="handleReset"><ReloadOutlined />重置</a-button>
        </a-form-item>
        <a-form-item>
          <a-button
            type="primary"
            @click="visible = true"
            v-if="authInfo.imports == 1"
            ><CloudUploadOutlined />导入信息</a-button
          >
        </a-form-item>
      </a-form>
      <a-table
        :columns="columns"
        :dataSource="dataSource"
        :pagination="pagination"
        class="mt-3"
      />
    </a-card>
    <a-modal :visible="visible" @cancel="visible = false" @ok="handleOk">
      <div>
        <div>
          <span>1.下载批量导入模版</span>
          <a-divider />
        </div>
        <div class="mb-5">
          <div>
            <span>根据提示信息完善表格内容</span>
          </div>
          <a-button
            type="primary"
            :icon="h(DownloadOutlined)"
            class="mt-3"
            @click="downloadTemplate"
            >客户标签导入模版.xls</a-button
          >
        </div>
        <div>
          <span>2.客户标签导入模版</span>
          <a-divider />
        </div>
        <a-upload-dragger
          v-model="fileList"
          name="file"
          :multiple="true"
          action="/api/ChargeSystem/customerLabel/verifyCustomerLabel"
          :headers="header"
          @change="handleChange"
          @drop="handleDrop"
          :beforeUpload="beforeUpload"
          accept=".xls,.xlsx,.et"
          class="mt-3"
        >
          <p class="ant-upload-drag-icon">
            <inbox-outlined></inbox-outlined>
          </p>
          <p class="ant-upload-text">点击/拖拽文件上传</p>
          <p class="ant-upload-hint">
            请将填写好的文件拖拽至此，或点击选择文件
          </p>
          <p class="ant-upload-hint">
            (仅支持.xls、.xlsx、.et格式文件，文件大小限制2MB以内)
          </p>
        </a-upload-dragger>
      </div>
    </a-modal>
  </div>
</template>
<script setup lang="ts">
import { ref, reactive, h } from 'vue';
import {
  SearchOutlined,
  ReloadOutlined,
  CloudUploadOutlined,
  DownloadOutlined,
  InboxOutlined,
} from '@ant-design/icons-vue';
import { useAccessStore } from '@vben/stores';
import { message } from 'ant-design-vue';
import {
  getCustomerLabelImport,
  importCustomerLabel_two,
} from '#/api/core/customerInformation';
import { getAccountButtonAuth } from '#/api/core/auth';
import { useRoute } from 'vue-router';
import dayjs from 'dayjs';
import { DictSelect } from '#/components/DictSelect';
import { getOperatorApi } from '#/api/core/statistical';
import { getCompanyTree } from '#/api/core/develop';

const authInfo = ref<any>({});
const router = useRoute();
const getAuth = () => {
  const query = {
    pageId: router.meta.id,
    userId: localStorage.getItem('userId'),
  };
  getAccountButtonAuth(query).then((res: any) => {
    // console.log(res)
    authInfo.value = res.data.data;
  });
  // console.log(router);
};
getAuth();

const comanyList = ref([]);
const getTableData = () => {
  getCompanyTree().then((res: any) => {
    // console.log(res);
    // 递归处理树形数据，保持层级结构
    const processTreeData = (tree: any[]): any[] => {
      // console.log(tree)
      return tree.map((item: any) => {
        const processedItem = {
          key: item.id,
          label: item.name,
          value: item.id,
          isLeaf: item.children && item.children.length > 0 ? false : true,
          children: [],
        };

        // 如果存在children，递归处理子节点
        if (item.children && item.children.length > 0) {
          processedItem.children = processTreeData(item.children);
        }

        return processedItem;
      });
    };

    const treeData = processTreeData([res.data]);
    comanyList.value = treeData;
    // console.log(comanyList.value);
  });
};
getTableData();
const selectList = ref([]);
const getList = () => {
  getOperatorApi(null)
    .then((res: any) => {
      // console.log(res);
      selectList.value = res.map((item: any) => {
        return {
          id: item.id,
          value: item.id,
          title: item.name,
          key: item.id,
          isLeaf: !!item.userId, // 如果有userId说明是叶子节点
        };
      });
    })
    .catch((error) => {
      console.error('获取操作人员列表失败:', error);
      message.error('获取操作人员列表失败');
    });
};
getList();
const onLoadData = (treeNode: any) => {
  return new Promise((resolve) => {
    // console.log(treeNode);
    // 如果是叶子节点，直接返回
    if (treeNode.isLeaf) {
      resolve(undefined);
      return;
    }

    // 加载子节点数据
    getOperatorApi(treeNode.id)
      .then((res: any) => {
        const children = res.map((item: any) => {
          // console.log(item);
          return {
            id: item.userId ? item.userId : item.id,
            value: item.name ? item.name : item.name,
            title: item.name,
            key: item.userId ? item.userId : item.id,
            isLeaf: !!item.userId, // 如果有userId说明是叶子节点
          };
        });

        // 找到对应的节点并更新其children
        const updateNode = (nodes: any[]) => {
          for (let node of nodes) {
            if (node.key === treeNode.id) {
              node.children = children;
              return true;
            }
            if (node.children && updateNode(node.children)) {
              return true;
            }
          }
          return false;
        };

        updateNode(selectList.value);
        selectList.value = [...selectList.value];
        // console.log(selectList.value);
        resolve(undefined);
      })
      .catch((error) => {
        console.error('加载子节点失败:', error);
        message.error('加载子节点失败');
        resolve(undefined);
      });
  });
};
const searchForm = reactive({
  operatorId: '',
  companyId: '',
  fileName: '',
  fileType: '',
  importStatus: '',
  importDate: '',
});

// 初始搜索表单数据备份
const initialSearchForm = {
  userId: '',
  orgId: '',
  fileName: '',
  fileType: '',
  importResult: '',
  importDate: null,
};
const columns = [
  {
    title: '文件名',
    dataIndex: 'fileName',
    key: 'fileName',
  },
  {
    title: '文件数',
    dataIndex: 'fileNumber',
    key: 'fileNumber',
  },
  {
    title: '操作人',
    dataIndex: 'operator',
    key: 'operator',
  },
  {
    title: '机构',
    dataIndex: 'companyName',
    key: 'companyName',
  },
  {
    title: '导入结果',
    dataIndex: 'importStatus',
    key: 'importStatus',
  },
  {
    title: '操作日期',
    dataIndex: 'operateTime',
    key: 'operateTime',
  },
];
// 假数据
const mockData = [
  {
    id: 1,
    fileName: '客户标签导入文件_20241201.xlsx',
    fileNum: 1250,
    userId: '张三',
    orgId: '北京分公司',
    importResult: '成功',
    importDate: '2024-12-01 10:30:00',
  },
  {
    id: 2,
    fileName: '用户信息批量更新.xls',
    fileNum: 890,
    userId: '李四',
    orgId: '上海分公司',
    importResult: '失败',
    importDate: '2024-11-30 14:20:00',
  },
  {
    id: 3,
    fileName: '客户分类标签.xlsx',
    fileNum: 2100,
    userId: '王五',
    orgId: '广州分公司',
    importResult: '成功',
    importDate: '2024-11-29 09:15:00',
  },
  {
    id: 4,
    fileName: 'VIP客户标签导入.et',
    fileNum: 567,
    userId: '赵六',
    orgId: '深圳分公司',
    importResult: '部分成功',
    importDate: '2024-11-28 16:45:00',
  },
  {
    id: 5,
    fileName: '新客户标签分类.xlsx',
    fileNum: 1800,
    userId: '钱七',
    orgId: '成都分公司',
    importResult: '成功',
    importDate: '2024-11-27 11:30:00',
  },
];

const dataSource = ref();
const allData = ref(); // 保存所有数据用于搜索
const pagination = reactive({
  current: 1,
  pageSize: 10,
  total: mockData.length,
  showSizeChanger: true,
  showQuickJumper: true,
  showTotal: (total: number) => `共 ${total} 条`,
  onChange: (page: number, pageSize: number) => {
    pagination.current = page;
    pagination.pageSize = pageSize;
    handleSearch();
  },
});
const visible = ref(false);
const fileList = ref([]);
const accessStore = useAccessStore();
const header = {
  Authorization: accessStore.accessToken || localStorage.getItem('token'),
};
const downloadTemplate = () => {
  // 从public目录下下载文件
  // window.location.href = '/public/开关栓状态导入模版.xls';
  const templatePath = '/Execl/客户标签导入模板.xls';
  const link = document.createElement('a');
  link.href = templatePath;
  link.download = templatePath.split('/').pop() || '';
  document.body.append(link);
  link.click();
  link.remove();
};

const beforeUpload = (file: File) => {
  const isExcel =
    file.type === 'application/vnd.ms-excel' ||
    file.type ===
      'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet';
  if (!isExcel) {
    message.error('只能上传 .xls, .xlsx, .et 格式的文件!');
  }
  const isLt2M = file.size / 1024 / 1024 < 2;
  if (!isLt2M) {
    message.error('文件大小不能超过 2MB!');
  }
  return isExcel && isLt2M;
};
const fileLocation = ref('');
const fileName = ref('');
const fileNumber = ref('');
const handleChange = (info: any) => {
  if (info.file.status === 'done') {
    if (info.file.response && info.file.response.code === 0) {
      message.success(`${info.file.name} 文件上传成功`);
      fileLocation.value = info.file.response.data.fileLocation;
      fileName.value = info.file.response.data.fileName;
      fileNumber.value = info.file.response.data.fileNumber;
    } else {
      message.error(
        `${info.file.name} 文件上传失败: ${info.file.response ? info.file.response.message : '未知错误'}`,
      );
    }
  } else if (info.file.status === 'error') {
    message.error(`${info.file.name} 文件上传失败.`);
  }
};
// 选项数据
const userOptions = ref([
  { label: '张三', value: '张三' },
  { label: '李四', value: '李四' },
  { label: '王五', value: '王五' },
  { label: '赵六', value: '赵六' },
  { label: '钱七', value: '钱七' },
]);

const orgOptions = ref([
  { label: '北京分公司', value: '北京分公司' },
  { label: '上海分公司', value: '上海分公司' },
  { label: '广州分公司', value: '广州分公司' },
  { label: '深圳分公司', value: '深圳分公司' },
  { label: '成都分公司', value: '成都分公司' },
]);

const fileTypeOptions = ref([
  { label: 'Excel文件(.xlsx)', value: 'xlsx' },
  { label: 'Excel文件(.xls)', value: 'xls' },
  { label: 'WPS表格(.et)', value: 'et' },
]);

// 搜索功能
const handleSearch = () => {
  const query = {
    page: pagination.current,
    limit: pagination.pageSize,
    operatorId: searchForm.operatorId,
    companyId: searchForm.companyId,
    fileName: searchForm.fileName,
    importStatus: searchForm.importStatus,
    importDate: searchForm.importDate
      ? dayjs(searchForm.importDate).format('YYYY-MM-DD')
      : '',
  };
  getCustomerLabelImport(query).then((res: any) => {
    console.log(res);
    dataSource.value = res.data.data;
    pagination.total = res.data.count;
  });
};

// 重置功能
const handleReset = () => {
  Object.assign(searchForm, initialSearchForm);
  dataSource.value = [...allData.value];
  pagination.total = allData.value.length;
  pagination.current = 1;

  message.success('重置成功');
};

const handleDrop = (e: DragEvent) => {
  console.log(e);
};
const handleOk = () => {
  importCustomerLabel_two({
    fileLocation: fileLocation.value,
    fileName: fileName.value,
    fileNumber: fileNumber.value,
  }).then((res: any) => {
    console.log(res);
    if (res.data.code === 200) {
      message.success(res.data.msg);
      handleSearch();
      visible.value = false;
    } else {
      message.error('导入失败');
    }
  });
};
</script>
<style scoped></style>
